package com.aletto.general_store.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.aletto.general_store.GeneralStoreApplication;
import com.aletto.general_store.data.entities.WalletAccount;
import com.google.gson.Gson;

public class LocalConfigStore {

    private static final
    String USER_TOKEN = "USER_TOKEN",     // 当前用户token
            USER_ID = "USER_ID",     // 当前用户id
            ACCOUNT = "ACCOUNT"; // 头像

    private static LocalConfigStore sLocalConfigStore;

    public static LocalConfigStore getInstance() {
        if (sLocalConfigStore == null) {
            synchronized (LocalConfigStore.class) {
                if (sLocalConfigStore == null) {
                    sLocalConfigStore = new LocalConfigStore();
                }
            }
        }

        return sLocalConfigStore;
    }


    private String mUserToken;
    private final SharedPreferences mPreferences;

    private LocalConfigStore() {
        mPreferences = GeneralStoreApplication.sInstance.getSharedPreferences("local_config_store", Context.MODE_PRIVATE);
    }

    public void setWallet(WalletAccount walletAccount) {
        mPreferences.edit()
                .putString(ACCOUNT, new Gson().toJson(walletAccount))
                .apply();
    }

    public void clearWallet() {
        mPreferences.edit()
                .remove(ACCOUNT)
                .apply();
    }

    public WalletAccount getWallet() {
        String data = mPreferences.getString(ACCOUNT, null);
        if (data != null) {
            return new Gson().fromJson(data, WalletAccount.class);
        }

        return null;
    }

    public String getToken() {
        if (TextUtils.isEmpty(mUserToken)) {
            mUserToken = mPreferences.getString(USER_TOKEN, "");
        }

        return mUserToken;
    }

    public void saveToken(String token) {
        mUserToken = token;
        mPreferences.edit().putString(USER_TOKEN, token).apply();
    }

    public void saveContractAddress(String address) {
        mPreferences.edit().putString("saveContractAddress", address).apply();
    }

    public String getContractAddress() {
        return mPreferences.getString("saveContractAddress", "");
    }

    public void clearToken() {
        mUserToken = null;
        mPreferences.edit().remove(USER_TOKEN).apply();
    }

    public void saveID(String id) {
        mPreferences.edit().putString(USER_ID, id).apply();
    }

    public String getUserID() {
        return mPreferences.getString(USER_ID, "");
    }

    public boolean isLogin() {

        return !TextUtils.isEmpty(getToken());
    }

}
